import { ref, computed } from "vue";
import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", {
  state: () => ({
    cart: [],
  }),
  getters: {},
  actions: {
    addCar(state) {
      var index = this.cart.findIndex((item) => item._id == state._id);
      console.log(index);
      if (index == -1) {
        state.num = 1; // 新增
        this.cart.push(state);
      } else {
        this.cart[index].num++;
      }
    },
    delCar(state) {
      if (state.num <= 0) {
        this.cart.splice(this.cart.indexOf(state), 1);
      } else {
        var index = this.cart.findIndex((item) => item._id == state._id);
        this.cart[index].num--;
      }
    },
  },
  persist: true,
});
